<?php
namespace app\controller;

use app\BaseController;
use think\Request;
use app\model\Note;
use app\model\User;
use app\model\Reminder;
use think\facade\Filesystem;
use app\model\Project;

class NoteController extends BaseController
{
    /**
     * 验证用户权限
     * @param Request $request
     * @return User|false
     */
    protected function verifyUser(Request $request)
    {
        // 尝试通过Token验证
        $user = UserController::getUserFromToken($request);
        if ($user) {
            return $user;
        }

        // 尝试通过Reminder Key验证
        $reminderKey = $request->header('X-Reminder-Key');
        if ($reminderKey) {
            $user = User::where('reminder_key', $reminderKey)->find();
            if ($user) {
                return $user;
            }
        }

        return false;
    }

    /**
     * 通过Operation Key验证提醒权限
     * @param string $key
     * @return Reminder|false
     */
    protected function verifyOperationKey($key)
    {
        if (empty($key)) {
            return false;
        }

        return Reminder::where('operation_key', $key)->find();
    }

    /**
     * 获取笔记列表
     */
    public function index(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $reminderId = $request->param('reminder_id');
        $importance = $request->param('importance');
        $source = $request->param('source');
        $projectId = $request->param('project_id');
        $keyword = $request->param('keyword'); // 新增关键词搜索参数
        $page = $request->param('page', 1);
        $pageSize = $request->param('page_size', 10);

        $query = Note::where('user_id', $user->id);

        if ($reminderId) {
            $query->where('reminder_id', $reminderId);
        }
        if ($importance) {
            $query->where('importance', $importance);
        }
        if ($source) {
            $query->where('source', $source);
        }
        if ($projectId) {
            $query->where('project_id', $projectId);
        }
        
        // 关键词搜索功能
        if (!empty($keyword)) {
            $keyword = trim($keyword);
            $query->where(function($query) use ($keyword) {
                $query->whereOr([
                    ['title', 'like', "%{$keyword}%"],           // 搜索标题
                    ['content', 'like', "%{$keyword}%"],         // 搜索内容
                    ['summary', 'like', "%{$keyword}%"],         // 搜索摘要
                    ['keywords', 'like', "%{$keyword}%"]         // 搜索关键词字段
                ]);
            });
        }

        $notes = $query->order('created_at', 'desc')
            ->paginate([
                'list_rows' => $pageSize,
                'page' => $page
            ]);

        // 格式化笔记数据
        $formattedNotes = array_map(function($note) {
            $data = $note->toArray();
            // 格式化时间字段
            $data['created_at'] = date('Y-m-d H:i:s', $note->created_at);
            $data['updated_at'] = date('Y-m-d H:i:s', $note->updated_at);
            // 添加状态文本
            $data['importance_text'] = $this->getImportanceText($note->importance);
            $data['source_text'] = $this->getSourceText($note->source);
            return $data;
        }, $notes->items());

        return json([
            'status' => 200,
            'data' => [
                'total' => $notes->total(),
                'current_page' => $notes->currentPage(),
                'last_page' => $notes->lastPage(),
                'notes' => $formattedNotes
            ]
        ]);
    }

    /**
     * 创建笔记
     */
    public function create(Request $request)
    {
        // 尝试通过Operation Key验证
        $operationKey = $request->param('key') ?? $request->post('key');
        $reminder = null;
        
        if ($operationKey) {
            $reminder = $this->verifyOperationKey($operationKey);
            if (!$reminder) {
                return json(['status' => 401, 'message' => '无效的操作密钥']);
            }
        } else {
            // 尝试其他验证方式
            $user = $this->verifyUser($request);
            if (!$user) {
                return json(['status' => 401, 'message' => '未授权访问']);
            }
        }

        $data = $request->post();
        if (empty($data['content'])) {
            return json(['status' => 400, 'message' => '笔记内容不能为空']);
        }

        try {
            $note = new Note;
            // 如果是通过Operation Key验证的，使用提醒所属的用户ID和提醒ID
            if ($reminder) {
                $note->user_id = $reminder->user_id;
                $note->reminder_id = $reminder->id;
            } else {
                $note->user_id = $user->id;
                $note->reminder_id = $data['reminder_id'] ?? null;
            }
            
            // 设置标题（如果未提供，则使用内容的前20个字符）
            $note->title = $data['title'] ?? mb_substr($data['content'], 0, 20) . '...';
            $note->content = $data['content'];
            
            // 设置摘要（如果提供）
            if (!empty($data['summary'])) {
                $note->summary = $data['summary'];
                $note->is_summarized = true;  // 标记为已有摘要
            }
            
            $note->importance = $data['importance'] ?? Note::IMPORTANCE_NORMAL;
            $note->source = $data['source'] ?? Note::SOURCE_USER;

            // 设置来源URL（会自动通过修改器格式化）
            if (!empty($data['source_url'])) {
                $note->source_url = $data['source_url'];
            }

            // 处理图片
            if (!empty($data['images'])) {
                $note->images = $data['images'];
                // $note->images = $this->processUploadedFiles($data['images'], 'images');
            }

            // 处理文件
            if (!empty($data['files'])) {
                // $note->files = $this->processUploadedFiles($data['files'], 'files');
                $note->files = $data['files'];
            }

            // 处理关键词
            if (!empty($data['keywords'])) {
                $note->setKeywords(is_array($data['keywords']) ? $data['keywords'] : explode(',', $data['keywords']));
            }

            // 处理项目关联
            if (isset($data['project_id'])) {
                if ($data['project_id'] === 'A') {
                    // AI自动判断项目
                    $projectId = $this->autoDetectProject($data['title'], $data['content']);
                    $note->project_id = $projectId;
                    if ($projectId) {
                        $note->recordAiHistory('auto_project', "AI自动关联到项目ID: {$projectId}");
                    }
                } else {
                    $note->project_id = $data['project_id'];
                }
            }
            
            if (isset($data['reminder_id'])) {
                $note->reminder_id = $data['reminder_id'];
            }

            $note->save();

            // 记录操作日志（仅当使用Token或Reminder Key时）
            if (!$reminder) {
                UserController::logOperation($note->user_id, 'create_note', "创建笔记", $request);
            }

            return json([
                'status' => 200,
                'message' => '笔记创建成功',
                'data' => $note
            ]);
        } catch (\Exception $e) {
            return json(['status' => 500, 'message' => '创建失败：' . $e->getMessage()]);
        }
    }

    /**
     * 更新笔记
     */
    public function update(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $noteId = $request->param('id');
        $data = $request->post();

        $note = Note::where('id', $noteId)
            ->where('user_id', $user->id)
            ->find();

        if (!$note) {
            return json(['status' => 404, 'message' => '笔记不存在或无权限']);
        }

        try {
            if (isset($data['title'])) {
                $note->title = $data['title'];
            } elseif (isset($data['content'])) {
                // 如果更新了内容但没有提供标题，则自动更新标题
                $note->title = mb_substr($data['content'], 0, 20) . '...';
            }
            if (isset($data['content'])) {
                $note->content = $data['content'];
            }
            if (isset($data['importance'])) {
                $note->importance = $data['importance'];
            }
            if (isset($data['keywords'])) {
                $note->setKeywords(is_array($data['keywords']) ? $data['keywords'] : explode(',', $data['keywords']));
            }
            if (isset($data['files'])) {
                $note->files = $data['files'];
            }

            // 处理新上传的图片
            if (!empty($data['new_images'])) {
                $currentImages = $note->images ?: [];
                $newImages = $this->processUploadedFiles($data['new_images'], 'images');
                $note->images = array_merge($currentImages, $newImages);
            }

            // 处理新上传的文件
            if (!empty($data['new_files'])) {
                $currentFiles = $note->files ?: [];
                $newFiles = $this->processUploadedFiles($data['new_files'], 'files');
                $note->files = array_merge($currentFiles, $newFiles);
            }

            // 更新来源URL（会自动通过修改器格式化）
            if (isset($data['source_url'])) {
                $note->source_url = $data['source_url'];
            }

            // 更新项目关联
            if (isset($data['project_id'])) {
                if ($data['project_id'] === 'A') {
                    // AI自动判断项目
                    $projectId = $this->autoDetectProject($note->title, $note->content);
                    $note->project_id = $projectId;
                    if ($projectId) {
                        $note->recordAiHistory('auto_project', "AI自动关联到项目ID: {$projectId}");
                    }
                } else {
                    $note->project_id = $data['project_id'];
                }
            }
            if (isset($data['reminder_id'])) {
                $note->reminder_id = $data['reminder_id'];
            }

            $note->save();

            UserController::logOperation($user->id, 'update_note', "更新笔记", $request);

            return json(['status' => 200, 'message' => '更新成功']);
        } catch (\Exception $e) {
            return json(['status' => 500, 'message' => '更新失败：' . $e->getMessage()]);
        }
    }

    /**
     * 删除笔记
     */
    public function delete(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $noteId = $request->param('id');

        $note = Note::where('id', $noteId)
            ->where('user_id', $user->id)
            ->find();

        if (!$note) {
            return json(['status' => 404, 'message' => '笔记不存在或无权限']);
        }

        try {
            $note->delete();

            UserController::logOperation($user->id, 'delete_note', "删除笔记", $request);

            return json(['status' => 200, 'message' => '删除成功']);
        } catch (\Exception $e) {
            return json(['status' => 500, 'message' => '删除失败：' . $e->getMessage()]);
        }
    }

    /**
     * 处理上传的文件
     */
    private function processUploadedFiles($files, $type)
    {
        $results = [];
        $storage = new \app\service\StorageService();

        foreach ($files as $file) {
            $tempPath = $file->getRealPath();
            $extension = $file->getOriginalExtension();
            $saveAs = $type . '/' . date('Ymd') . '/' . uniqid() . '.' . $extension;

            $result = $storage->upload($tempPath, $saveAs);
            if ($result) {
                $results[] = [
                    'name' => $file->getOriginalName(),
                    'path' => $result['path'],
                    'url' => $result['url'],
                    'size' => $file->getSize(),
                    'type' => $file->getMime()
                ];
            }
        }
        return $results;
    }

    /**
     * AI自动总结笔记
     */
    public function summarize(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $noteId = $request->param('id');
        $note = Note::where('id', $noteId)
            ->where('user_id', $user->id)
            ->find();

        if (!$note) {
            return json(['status' => 404, 'message' => '笔记不存在或无权限']);
        }

        try {
            // TODO: 调用AI接口进行总结
            // 这里需要集成具体的AI服务，如OpenAI API
            $summary = "这是AI生成的总结...";  // 临时示例
            $keywords = ["关键词1", "关键词2"];  // 临时示例

            $note->summary = $summary;
            $note->setKeywords($keywords);
            $note->is_summarized = true;
            $note->save();

            UserController::logOperation($user->id, 'summarize_note', "AI总结笔记", $request);

            return json([
                'status' => 200,
                'message' => '笔记总结完成',
                'data' => [
                    'summary' => $summary,
                    'keywords' => $keywords
                ]
            ]);
        } catch (\Exception $e) {
            return json(['status' => 500, 'message' => '总结失败：' . $e->getMessage()]);
        }
    }

    /**
     * 搜索笔记
     */
    public function search(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $keyword = $request->param('keyword');
        $page = $request->param('page', 1);
        $pageSize = $request->param('page_size', 10);

        if (empty($keyword)) {
            return json(['status' => 400, 'message' => '搜索关键词不能为空']);
        }

        try {
            $query = Note::where('user_id', $user->id)
                ->where(function ($query) use ($keyword) {
                    $query->whereOr([
                        ['content', 'like', "%{$keyword}%"],
                        ['summary', 'like', "%{$keyword}%"],
                        ['keywords', 'like', "%{$keyword}%"]
                    ]);
                });

            $notes = $query->order('created_at', 'desc')
                ->paginate([
                    'list_rows' => $pageSize,
                    'page' => $page
                ]);

            return json([
                'status' => 200,
                'data' => [
                    'total' => $notes->total(),
                    'current_page' => $notes->currentPage(),
                    'last_page' => $notes->lastPage(),
                    'notes' => $notes->items()
                ]
            ]);
        } catch (\Exception $e) {
            return json(['status' => 500, 'message' => '搜索失败：' . $e->getMessage()]);
        }
    }

    /**
     * 分享笔记
     */
    public function share(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $noteId = $request->param('id');
        $note = Note::where('id', $noteId)
            ->where('user_id', $user->id)
            ->find();

        if (!$note) {
            return json(['status' => 404, 'message' => '笔记不存在或无权限']);
        }

        try {
            // 生成分享链接
            $shareKey = md5(uniqid($note->id, true));
            $note->share_key = $shareKey;
            $note->share_expire_time = time() + 7 * 86400; // 7天后过期
            $note->save();

            $shareUrl = config('app.url') . "/note/share/" . $shareKey;

            UserController::logOperation($user->id, 'share_note', "分享笔记", $request);

            return json([
                'status' => 200,
                'message' => '分享链接生成成功',
                'data' => [
                    'share_url' => $shareUrl,
                    'expire_time' => date('Y-m-d H:i:s', $note->share_expire_time)
                ]
            ]);
        } catch (\Exception $e) {
            return json(['status' => 500, 'message' => '分享失败：' . $e->getMessage()]);
        }
    }

    /**
     * 查看分享的笔记
     */
    public function viewShared(Request $request, $shareKey)
    {
        $note = Note::where('share_key', $shareKey)
            ->where('share_expire_time', '>', time())
            ->find();

        if (!$note) {
            return json(['status' => 404, 'message' => '分享链接不存在或已过期']);
        }

        return json([
            'status' => 200,
            'data' => [
                'title' => $note->title,
                'content' => $note->content,
                'summary' => $note->summary,
                'keywords' => $note->getKeywordsArray(),
                'created_at' => date('Y-m-d H:i:s', $note->created_at)
            ]
        ]);
    }

    /**
     * 导出笔记
     */
    public function export(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $noteIds = $request->param('note_ids');
        $format = $request->param('format', 'markdown'); // 支持 markdown, pdf, html

        if (empty($noteIds)) {
            return json(['status' => 400, 'message' => '请选择要导出的笔记']);
        }

        try {
            $notes = Note::where('user_id', $user->id)
                ->whereIn('id', explode(',', $noteIds))
                ->select();

            if ($notes->isEmpty()) {
                return json(['status' => 404, 'message' => '未找到要导出���笔记']);
            }

            // 根据格式导出笔记
            $exportFile = $this->exportNotes($notes, $format);

            UserController::logOperation($user->id, 'export_note', "导出笔记", $request);

            return json([
                'status' => 200,
                'message' => '导出成功',
                'data' => [
                    'file_url' => $exportFile
                ]
            ]);
        } catch (\Exception $e) {
            return json(['status' => 500, 'message' => '导出失败：' . $e->getMessage()]);
        }
    }

    /**
     * 导出笔记内容
     */
    private function exportNotes($notes, $format)
    {
        $content = '';
        foreach ($notes as $note) {
            $content .= "# {$note->title}\n\n";
            $content .= $note->content . "\n\n";
            if ($note->summary) {
                $content .= "## 摘要\n\n{$note->summary}\n\n";
            }
            if ($note->keywords) {
                $content .= "关键词：" . implode(', ', $note->getKeywordsArray()) . "\n\n";
            }
            $content .= "---\n\n";
        }

        $fileName = 'notes_' . date('YmdHis') . '.' . $format;
        $filePath = public_path('exports/' . $fileName);

        // 根据格式处理内容
        switch ($format) {
            case 'pdf':
                // TODO: 使用PDF生成库处理
                break;
            case 'html':
                $content = $this->markdownToHtml($content);
                break;
        }

        file_put_contents($filePath, $content);
        return '/exports/' . $fileName;
    }

    /**
     * Markdown转HTML
     */
    private function markdownToHtml($markdown)
    {
        // TODO: 使用Markdown解析库
        return "<html><body>{$markdown}</body></html>";
    }

    /**
     * 获取笔记详情
     */
    public function detail(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $noteId = $request->param('id');
        if (empty($noteId)) {
            return json(['status' => 400, 'message' => '笔记ID不能为空']);
        }

        try {
            // 获取笔记信息
            $note = Note::where('id', $noteId)
                ->where('user_id', $user->id)
                ->find();

            if (!$note) {
                return json(['status' => 404, 'message' => '笔记不存在']);
            }

            // 获取关联的提醒信息（如果有）
            $reminder = null;
            if ($note->reminder_id) {
                $reminder = Reminder::where('id', $note->reminder_id)->find();
            }

            // 获取关联的项目信息（如果有）
            $project = null;
            if ($note->project_id) {
                $project = Project::where('id', $note->project_id)->find();
            }

            // 格式化笔记数据
            $data = [
                'id' => $note->id,
                'title' => $note->title,
                'content' => $note->content,
                'summary' => $note->summary,
                'keywords' => $note->keywords,
                'importance' => $note->importance,
                'importance_text' => $this->getImportanceText($note->importance),
                'source' => $note->source,
                'source_text' => $this->getSourceText($note->source),
                'source_url' => $note->source_url,
                'is_summarized' => $note->is_summarized,
                'images' => is_array($note->images) ? $note->images : [],
                'files' => is_array($note->files) ? $note->files : [],
                'created_at' => date('Y-m-d H:i:s', $note->created_at),
                'updated_at' => date('Y-m-d H:i:s', $note->updated_at),
                'reminder' => $reminder ? [
                    'id' => $reminder->id,
                    'title' => $reminder->title,
                    'due_date' => $reminder->due_date,
                    'status' => $reminder->is_completed ? '已完成' : '进行中'
                ] : null,
                'project' => $project ? [
                    'id' => $project->id,
                    'name' => $project->name,
                    'status' => $project->status,
                    'status_text' => Project::$statusMap[$project->status] ?? '未知状态'
                ] : null,
                'ai_history' => $note->getAiHistoryArray()
            ];

            // 记录操作日志
            UserController::logOperation($user->id, 'view_note', "查看笔记：{$note->title}", $request);

            return json([
                'status' => 200,
                'data' => $data
            ]);

        } catch (\Exception $e) {
            \think\facade\Log::error('获取笔记详情失败：' . $e->getMessage());
            return json(['status' => 500, 'message' => '获取笔记详情失败：' . $e->getMessage()]);
        }
    }

    /**
     * 获取笔记草稿（与 detail 相同功能）
     */
    public function draft(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $noteId = $request->param('id');
        if (empty($noteId)) {
            return json(['status' => 400, 'message' => '笔记ID不能为空']);
        }

        try {
            // 获取笔记信息
            $note = Note::where('id', $noteId)
                ->where('user_id', $user->id)
                ->find();

            if (!$note) {
                return json(['status' => 404, 'message' => '笔记不存在']);
            }

            // 获取关联的提醒信息（如果有）
            $reminder = null;
            if ($note->reminder_id) {
                $reminder = Reminder::where('id', $note->reminder_id)->find();
            }

            // 获取关联的项目信息（如果有）
            $project = null;
            if ($note->project_id) {
                $project = Project::where('id', $note->project_id)->find();
            }

            // 格式化笔记数据（与 detail 相同）
            $data = [
                'id' => $note->id,
                'title' => $note->title,
                'content' => $note->content,
                'summary' => $note->summary,
                'keywords' => $note->keywords,
                'importance' => $note->importance,
                'importance_text' => $this->getImportanceText($note->importance),
                'source' => $note->source,
                'source_text' => $this->getSourceText($note->source),
                'source_url' => $note->source_url,
                'is_summarized' => $note->is_summarized,
                'images' => is_array($note->images) ? $note->images : [],
                'files' => is_array($note->files) ? $note->files : [],
                'created_at' => date('Y-m-d H:i:s', $note->created_at),
                'updated_at' => date('Y-m-d H:i:s', $note->updated_at),
                'reminder' => $reminder ? [
                    'id' => $reminder->id,
                    'title' => $reminder->title,
                    'due_date' => $reminder->due_date,
                    'status' => $reminder->is_completed ? '已完成' : '进行中'
                ] : null,
                'project' => $project ? [
                    'id' => $project->id,
                    'name' => $project->name,
                    'status' => $project->status,
                    'status_text' => Project::$statusMap[$project->status] ?? '未知状态'
                ] : null,
                'ai_history' => $note->getAiHistoryArray()
            ];

            // 记录操作日志（标记为草稿查看）
            UserController::logOperation($user->id, 'view_draft', "查看笔记草稿：{$note->title}", $request);

            return json([
                'status' => 200,
                'data' => $data
            ]);

        } catch (\Exception $e) {
            \think\facade\Log::error('获取笔记草稿失败：' . $e->getMessage());
            return json(['status' => 500, 'message' => '获取笔记草稿失败：' . $e->getMessage()]);
        }
    }

    /**
     * 自动保存笔记（保存或更新）
     */
    public function autoSave(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $data = $request->post();
        $noteId = $request->param('id') ?? $data['id'] ?? null;

        try {
            if ($noteId) {
                // 更新已存在的笔记
                $note = Note::where('id', $noteId)
                    ->where('user_id', $user->id)
                    ->find();

                if (!$note) {
                    return json(['status' => 404, 'message' => '笔记不存在或无权限']);
                }

                // 更新笔记字段（只更新提供的字段）
                if (isset($data['title']) && $data['title'] !== '') {
                    $note->title = $data['title'];
                }
                if (isset($data['content'])) {
                    $note->content = $data['content'];
                    // 如果更新了内容但没有提供标题，则自动更新标题
                    if (!isset($data['title']) || $data['title'] === '') {
                        $note->title = mb_substr($data['content'], 0, 20) . '...';
                    }
                }
                if (isset($data['summary'])) {
                    $note->summary = $data['summary'];
                    $note->is_summarized = !empty($data['summary']);
                }
                if (isset($data['importance']) && $data['importance'] !== '') {
                    $note->importance = $data['importance'];
                }
                if (isset($data['source_url'])) {
                    $note->source_url = $data['source_url'];
                }
                if (isset($data['keywords'])) {
                    $note->setKeywords(is_array($data['keywords']) ? $data['keywords'] : explode(',', $data['keywords']));
                }
                if (isset($data['project_id'])) {
                    if ($data['project_id'] === 'A') {
                        // AI自动判断项目
                        $projectId = $this->autoDetectProject($note->title, $note->content);
                        $note->project_id = $projectId;
                        if ($projectId) {
                            $note->recordAiHistory('auto_project', "AI自动关联到项目ID: {$projectId}");
                        }
                    } else {
                        $note->project_id = $data['project_id'];
                    }
                }
                if (isset($data['reminder_id'])) {
                    $note->reminder_id = $data['reminder_id'];
                }

                $note->save();

                // 记录操作日志
                UserController::logOperation($user->id, 'auto_save_note', "自动保存笔记：{$note->title}", $request);

                return json([
                    'status' => 200,
                    'message' => '笔记自动保存成功',
                    'data' => [
                        'id' => $note->id,
                        'title' => $note->title,
                        'updated_at' => date('Y-m-d H:i:s', $note->updated_at)
                    ]
                ]);

            } else {
                // 创建新笔记
                if (empty($data['content']) && empty($data['title'])) {
                    return json(['status' => 400, 'message' => '笔记内容和标题不能同时为空']);
                }

                $note = new Note;
                $note->user_id = $user->id;
                
                // 设置标题（如果未提供，则使用内容的前20个字符）
                $note->title = $data['title'] ?? mb_substr($data['content'] ?? '', 0, 20) . '...';
                $note->content = $data['content'] ?? '';
                
                // 设置摘要（如果提供）
                if (!empty($data['summary'])) {
                    $note->summary = $data['summary'];
                    $note->is_summarized = true;
                }
                
                $note->importance = $data['importance'] ?? Note::IMPORTANCE_NORMAL;
                $note->source = $data['source'] ?? Note::SOURCE_USER;

                // 设置来源URL
                if (!empty($data['source_url'])) {
                    $note->source_url = $data['source_url'];
                }

                // 处理关键词
                if (!empty($data['keywords'])) {
                    $note->setKeywords(is_array($data['keywords']) ? $data['keywords'] : explode(',', $data['keywords']));
                }

                // 处理项目关联
                if (isset($data['project_id'])) {
                    if ($data['project_id'] === 'A') {
                        // AI自动判断项目
                        $projectId = $this->autoDetectProject($note->title, $note->content);
                        $note->project_id = $projectId;
                        if ($projectId) {
                            $note->recordAiHistory('auto_project', "AI自动关联到项目ID: {$projectId}");
                        }
                    } else {
                        $note->project_id = $data['project_id'];
                    }
                }
                
                if (isset($data['reminder_id'])) {
                    $note->reminder_id = $data['reminder_id'];
                }

                $note->save();

                // 记录操作日志
                UserController::logOperation($user->id, 'auto_create_note', "自动创建笔记：{$note->title}", $request);

                return json([
                    'status' => 200,
                    'message' => '笔记自动创建成功',
                    'data' => [
                        'id' => $note->id,
                        'title' => $note->title,
                        'created_at' => date('Y-m-d H:i:s', $note->created_at),
                        'updated_at' => date('Y-m-d H:i:s', $note->updated_at)
                    ]
                ]);
            }

        } catch (\Exception $e) {
            \think\facade\Log::error('自动保存笔记失败：' . $e->getMessage());
            return json(['status' => 500, 'message' => '自动保存失败：' . $e->getMessage()]);
        }
    }

    /**
     * 获取重要程度文本
     */
    private function getImportanceText($importance)
    {
        $importanceMap = [
            Note::IMPORTANCE_NORMAL => '普通',
            Note::IMPORTANCE_IMPORTANT => '重要',
            Note::IMPORTANCE_CRITICAL => '关键'
        ];
        return $importanceMap[$importance] ?? '未知';
    }

    /**
     * 获取来源文本
     */
    private function getSourceText($source)
    {
        $sourceMap = [
            Note::SOURCE_USER => '用户手动',
            Note::SOURCE_AI => 'AI对话',
            Note::SOURCE_WEB => '网页内容'
        ];
        return $sourceMap[$source] ?? '未知';
    }

    /**
     * 新增AI自动检测项目的方法
     */
    private function autoDetectProject($title, $content)
    {
        try {
            // TODO: 实现实际的AI项目检测逻辑
            // 这里需要集成具体的AI服务
            return null;
        } catch (\Exception $e) {
            \think\facade\Log::error('AI检测项目失败：' . $e->getMessage());
            return null;
        }
    }
} 